package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.UserService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Reference
    private UserService userService;
    /**
     * 在网页上显示用户名
     * 能直接在框架里面获取
     * @return
     */
    @RequestMapping("/getUsername")
    public Result getUsername(){
        try {
          User  user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS,user.getUsername());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false, MessageConstant.GET_USERNAME_FAIL);

    }

    @RequestMapping("/findAll")
    public Result findAll(){
        try {
            List<com.itheima.pojo.User> lists= userService.findAll();
            return new Result(true,"数据查询成功！",lists);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"数据查询失败！");
        }
    }

    @RequestMapping("/getUserByRoleId")
    public Result getUserByRoleId(Integer id){
        try {
            List<Integer> list=userService.getUserByRoleId(id);
            return new Result(true,"用户数据查询成功！",list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"用户数据查询失败！");
        }
    }
}
